<?php
/* ******************************
 *	Transfer aJax actions
 * ******************************
 */

include('../../includes/classes/core.php');
 

$action	= $_REQUEST['act'];
$error	= '';
$data	= '';

switch ($action) {
    case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);

        break;
    case 'get_edit_page':
	    $rec_id		= $_REQUEST['id'];
		$page		= GetPage(GetTransfer($rec_id));

        $data 		= array('page'	=> $page);

        break;
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];

	    $rResult = mysql_query("SELECT 		`tr`.`id`,
											`tr`.`date`,
											`first`.`name`,
											`second`.`name`
								FROM 		`transfer` AS `tr`
								LEFT JOIN 	`object` AS `first`
								ON 			`tr`.`source_id` = `first`.`id`
								LEFT JOIN 	`object` AS `second`
								ON 			`tr`.`target_id` = `second`.`id`");

		$data = array(
			"aaData"	=> array()
		);

		if(!$rResult){
			$error = 'Invalid query: ' . mysql_error();
		}else{
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
				}
				$data['aaData'][] = $row;
			}

		}

        break;
    case 'save_trans':
		$rec_id			= $_REQUEST['id'];

    	$source_id		= $_REQUEST['so'];
		$target_id		= $_REQUEST['to'];

		$transfer_id = AddTransfer($rec_id, $source_id, $target_id);

		if(!$transfer_id){
			$error = 'პროდუქტის(ების) ტრანსფერი წარუმატებლად დასრულდა!';
		}else{

			$req = mysql_query("SELECT `production_id`,
									   `quantity`
								FROM `transfer_detail`
								WHERE `transfer_id` = $transfer_id");

			while( $res = mysql_fetch_assoc($req)){
				MakeTransfer($res['production_id'], $res['quantity'], $source_id, $target_id);
			}
		}

        break;
	case 'check_prod_list':
		$trans_id 		= $_REQUEST['id'];
		$check			= ChackProdList($trans_id);
		if($check){
			$error = 'პროდუქციის სია ცარიელია!';
		}

        break;
    case 'get_local_id':
		$local_id = GetLocalID();

		$data = array('local_id' => $local_id);

        break;
    case 'clear_db':
		ClearDB();

        break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Transfer Functions
 * ******************************
 */

function ClearDB()
{
	$req = mysql_query("SELECT	`id`
						FROM	`transfer_detail`
						WHERE	`transfer_id` NOT IN (SELECT `id` FROM `transfer`)");

	while( $res = mysql_fetch_assoc($req)){
		mysql_query("DELETE
					 FROM
						`transfer_detail`
					 WHERE
						`id` = '$res[id]'");
	}
}

function AddTransfer($rec_id, $source_id, $target_id)
{
	$c_data = date('Y-m-d H:i:s');

	GLOBAL $error;
	$result = mysql_query("INSERT IGNORE INTO `transfer` (`id`) VALUES ($rec_id)");
	if(!$result){
		$error = 'Invalid query: ' . mysql_error();
	}else{

		mysql_query("	UPDATE	`transfer`
						SET
							`date`			= '$c_data',
							`source_id`		= $source_id,
							`target_id`		= $target_id
						WHERE
						`id` = '$rec_id'");
	}

	if (!$result) {
		return false;
	}
	return $rec_id;
}

function MakeTransfer($prod_id, $quantity, $source_object, $target_object)
{
	global $error;

	$req_quantity	= $quantity;
	$c_date			= date('Y-m-d H:i:s');

	$res = mysql_query("SELECT   `reserve`.`id`,
								 `reserve`.`overhead_id`,
								 `reserve`.`price`,
								 `reserve`.`real_price`,
								 `reserve`.`vat`,
								 `reserve`.`quantity`,
	                             `reserve`.`sold`,  
								 `reserve`.`quantity` - `reserve`.`sold` AS `diff`
						FROM 	 `reserve`
						WHERE 	 `reserve`.`object_id` = '$source_object' && `reserve`.`production_id` = '$prod_id'						
	                    HAVING diff>0 
	    ORDER BY `reserve`.`create_date` ASC");

	while ($row = mysql_fetch_array($res)) {
		if ($req_quantity != 0) {
			if($row['diff'] > $req_quantity){

				$sum = $row['quantity'] - $req_quantity;

				mysql_query("UPDATE `reserve`
							 SET	`quantity` = $sum
							 WHERE	`id` = $row[id]" );

				mysql_query("INSERT INTO `reserve`
								(`object_id`, `overhead_id`, `production_id`, `quantity`, `price`, `real_price`, `vat`, `create_date`)
							VALUES
								($target_object, $row[overhead_id], $prod_id, $req_quantity, $row[price], $row[real_price], $row[vat], '$c_date')");

				$req_quantity = 0;

			}else if($row['diff'] == $req_quantity){

				$sum = $row['quantity'] - $req_quantity;

				mysql_query("UPDATE `reserve`
							 SET	`quantity` = $sum
							 WHERE	`id` = $row[id]" );

				mysql_query("INSERT INTO `reserve`
								(`object_id`, `overhead_id`, `production_id`, `quantity`, `price`, `real_price`, `vat`, `create_date`)
							VALUES
								($target_object, $row[overhead_id], $prod_id, $req_quantity, $row[price], $row[real_price], $row[vat], '$c_date')");

				$req_quantity = 0;

			}else{
				$sum = $row[sold];

				mysql_query("UPDATE `reserve`
							 SET	`quantity` = $sum
							 WHERE	`id` = $row[id]" );

				mysql_query("INSERT INTO `reserve`
								(`object_id`, `overhead_id`, `production_id`, `quantity`, `price`, `real_price`, `vat`, `create_date`)
							VALUES
								($target_object, $row[overhead_id], $prod_id, $row[quantity], $row[price], $row[real_price], $row[vat], '$c_date')");

				$req_quantity = $req_quantity - $row['diff'];

			}
		}
	}
}

function ChackProdList($trans_id)
{
	$check = false;
	$req = mysql_query("SELECT	`id`
						FROM	`transfer_detail`
						WHERE	`transfer_id` = '$trans_id'");

	if (mysql_num_rows($req) == 0){
		$check = true;
	}

	return $check;
}

function GetLocalID()
{
	GLOBAL $db;
	$local_id = $db->increment('transfer');

	return $local_id;
}

function GetObject($object_id)
{
	$data = '';
	$req = mysql_query("SELECT	`id`, `name`
						FROM	`object`
						WHERE	`object`.`type` != 1 && `object`.`type` != 5 && `object`.`type` != 7
						ORDER BY object.`name` DESC"); // <<<<---------------------Type!!!

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $object_id){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}
	return $data;
}

function GetTransfer($rec_id)
{
    $res = mysql_fetch_assoc(mysql_query("SELECT 	`id`,
    											 	`source_id`,
											     	`target_id`
									      FROM 		`transfer`
									      WHERE 	`id` = '$rec_id'"));
	return $res;
}

function GetPage($res = '')
{
	$data = '
	<!-- jQuery Dialog -->
    <div id="add-edit-prod-form" class="form-dialog" title="შემადგენლობა">
    	<!-- aJax -->
	</div>
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
			<table border="0" width="100%">
				<tr>
					<th><label for="source_object">საწყისი მდებარეობა</label></th>
					<th><label for="target_object">საბოლოო მდებარეობა</label></th>
				</tr>
				<tr>
					<th>
						<select id="source_object" class="idls address">' . GetObject($res['source_id']) . '</select>
					</th>
					<th>
						<select id="target_object" class="idls address">' . GetObject($res['target_id']) . '</select>
					</th>
				</tr>
			</table>
        </fieldset>

		<fieldset>
	    	<legend>პროდუქტი</legend>

		    <div class="inner-table">
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" class="overhead_container">
			        	<div id="button_area">
			        		<button id="add_button_prod">დამატება</button><button id="delete_button_prod">წაშლა</button>
			        	</div>
			            <div id="dynamic">
			                <table class="display" id="prod_list">
			                    <thead>
			                        <tr id="datatable_header">
			                            <th>ID</th>
			                            <th style="width : 100%">პროდუქტი</th>
			                            <th class="min">რაოდენობა</th>
			                            <th class="check">#</th>
			                        </tr>
			                    </thead>
			                    <thead>
			                        <tr class="search_header">
			                            <th class="colum_hidden">
			                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th></th>
										<th>
											<input type="checkbox" name="check-all" id="check-all-prod" style="margin-left: 13px;">
										</th>
			                        </tr>
			                    </thead>
			                </table>
			            </div>
			        </div>
			    </div>
			</div>
		</fieldset>
		<!-- ID -->
		<input type="hidden" id="trans_id" value="' . $res['id'] . '" />
		<input type="hidden" id="local_trans_id" />
    </div>
    ';

	return $data;
}
?>